package com.vincent.dao;

import com.vincent.common.enums.CacheEnum;
import com.vincent.model.ArticleWithBLOBs;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by vincent on 15-1-2.
 */
@Repository("articleDao")
public class ArticleDao {

    @Resource
    private ArticleMapper articleMapper;

    /**
     * 获取首页文章显示的id集合
     *
     * @param categoryId
     * @param topNum
     * @param isPublication
     * @return
     */
    @Cacheable(value = CacheEnum.ARTICLE_HOMEPAGE)
    public List<Integer> selectTopByCategoryId(int categoryId, int topNum, boolean isPublication) {
        return articleMapper.selectTopByCategory(categoryId, topNum, isPublication);
    }

    /**
     * 清除缓存
     */
    @CacheEvict(value = {CacheEnum.ARTICLE_HOMEPAGE, CacheEnum.ARTICLE_HOTEST}, allEntries = true)
    public void clearCache() {

    }

    /**
     * 获取文章列表分页的文章id集合
     *
     * @param startIndex
     * @param pageSize
     * @param categoryId
     * @param isPublication
     * @return
     */
    public List<Integer> selectPaginationIdList(int startIndex, int pageSize, Integer categoryId, Boolean isPublication) {
        return articleMapper.selectIdPagination(startIndex, pageSize, categoryId, isPublication);
    }

    /**
     * 根据id获取文章
     *
     * @param id
     * @return
     */
    @Cacheable(value = CacheEnum.ARTICLE,key = "#id+'article'")
    public ArticleWithBLOBs getArticleById(int id) {
        return articleMapper.selectByPrimaryKey(id);
    }

    @CacheEvict(value = CacheEnum.ARTICLE,allEntries = false,key = "#id+'article'")
    public void clearCacheById(int id){}

    /**
     * 获取文章数目
     *
     * @param categoryId
     * @param isPublication
     * @return
     */
    public int getArticlePagenationNum(Integer categoryId, Boolean isPublication) {
        return articleMapper.selectIdPaginationNum(categoryId, isPublication);
    }

    /**
     * 获取最热文章id集合
     *
     * @param num
     * @param categoryId
     * @param isPublication
     * @return
     */
    @Cacheable(value = CacheEnum.ARTICLE_HOTEST)
    public List<Integer> getHotestArticles(int num, int categoryId, boolean isPublication) {
        return articleMapper.selectHotestArticles(categoryId, num, isPublication);
    }

    /**
     * 删除文章
     * @param ids
     */
    public void deleteArticles(Integer[] ids) {
        articleMapper.deleteArticles(ids);
    }

    public void saveArticle(ArticleWithBLOBs article){
        articleMapper.insertSelective(article);
    }

    public void updateArticle(ArticleWithBLOBs article){
        articleMapper.updateByPrimaryKeySelective(article);
    }
}